package com.yzjs.common.util.httpclient;

import com.google.common.base.Joiner;
import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    private static final int SO_TIMEOUT = 3000;
    private static final String ENCODING = "UTF-8";

     public static String get(String url, List<NameValuePair> nvps) {
        url += "?" + Joiner.on("&").join(nvps);
       return   get(url,SO_TIMEOUT);
    }

  

    public static String get(String url, Integer timeoutMS) {
        HttpGet get = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(timeoutMS).setConnectionRequestTimeout(1000)
                .setSocketTimeout(timeoutMS).build();
        get.setConfig(requestConfig);
        CloseableHttpClient httpClient = HttpClientFactory.get();
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (response.getEntity() != null) {
                    return IOUtils.toString(response.getEntity().getContent(), ENCODING);
                }
                return null;
            } else
                return "fault";
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            if(response!=null){
                try{
                    response.close();
                }catch (Exception e){
                    e.printStackTrace();
//                    Map map=new HashMap(3);
//                    map.put("method", "HttpClient.get");
//                    map.put("url", url);
                    
                    
                }
            }
        }
        return null;
    }
    /**
     * post forms
     *
     * @param url
     * @param postData
     * @return
     */
    public static String post(String url, Map<String, String> postData) {
        if (postData != null) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : postData.entrySet()) {
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            return post(url, formparams);
        }
        return "fault";
    }

    public static String post(String url, Map<String, String> postData, int timeoutMS) {
        if (postData != null) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : postData.entrySet()) {
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            return post(url, formparams,timeoutMS);
        }
        return "fault";
    }


    public static String httpPostJson(String url, String json,int timeoutMS) throws IOException {
        String result = "";
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(timeoutMS).setConnectionRequestTimeout(timeoutMS)
                .setSocketTimeout(timeoutMS).build();
        httpPost.setConfig(requestConfig);

        CloseableHttpClient httpClient = HttpClientFactory.get();
        try {
            BasicResponseHandler handler = new BasicResponseHandler();
            StringEntity entity = new StringEntity(json, "utf-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            result = httpClient.execute(httpPost, handler);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



    public static String post(String url, List<NameValuePair> postData) {
        return post(url, postData, 4000);
    }

    /**
     * 打印异常的post
     * @param url
     * @param postData
     * @param timeoutMS
     * @return
     */
    public static String post(String url, List<NameValuePair> postData, int timeoutMS) {
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(timeoutMS).setConnectionRequestTimeout(1000)
                .setSocketTimeout(timeoutMS).build();
        post.setConfig(requestConfig);
        CloseableHttpClient httpClient = HttpClientFactory.get();
        CloseableHttpResponse response = null;
        try {
            if (null != postData && !postData.isEmpty()) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, Consts.UTF_8);
                post.setEntity(entity);
            }
            response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (response.getEntity() != null) {
                    return IOUtils.toString(response.getEntity().getContent(), ENCODING);
                }
                return "success";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if(response!=null){
                try{
                    response.close();
                }catch (Exception e){
                    e.printStackTrace();
                    Map map=new HashMap(8);
                    map.put("method", "HttpClient.post");
                    map.put("url", url);
                    if(postData!=null) {
                        map.put("postData", postData.toString());
                    }
                   // new LogException(e,map);
                }
            }
        }
        return "fault";
    }


    public static String post1(String url, List<NameValuePair> postData) {
        HttpPost post = null;
        post = new HttpPost(url);
        if (null != postData && !postData.isEmpty()) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, Consts.UTF_8);
            post.setEntity(entity);
        }
        CloseableHttpClient httpClient = HttpClientFactory.get();
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (response.getEntity() != null) {
                    return IOUtils.toString(response.getEntity().getContent(), ENCODING);
                }
                return "success";
            }
        }catch (Exception e){
            Map map=new HashMap();
            map.put("method", "httpUtils.post1");
            map.put("key", url);
            map.put("value", postData);
           //new LogException(e,map);
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    Map map=new HashMap();
                    map.put("method", "httpUtils.post1");
                    map.put("key", url);
                    map.put("value", postData);
                   // new LogException(e,map);
                }
            }
        }
        return "fault";
    }


   
    
  
}
